package com.ruoyi.controller;


import com.google.code.kaptcha.Producer;
import com.google.gson.Gson;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.domain.*;
import com.ruoyi.domain.Vo.VoiceVo;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.service.CaptchaService;
import com.ruoyi.service.DeviceService;
import com.ruoyi.service.IAdvOrdersdetailService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.utils.sign.Base64;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;

import static com.ruoyi.common.utils.file.FileUtils.checkAllowDownload;


/**
 * DeviceController
 *
 * @author ruoyi
 * @date 2024-05-13
 */
@RestController
    @RequestMapping("/system/device")
public class DeviceController extends BaseController {

    @Autowired
    private DeviceService deviceServiceImpl;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private CaptchaService captchaService;


    /**
     * 小程序端上传产品内容到设备功能
     * SyncRequest请求体
     * productIds 产品id数组
     * we_openid  openid
     */
    @PostMapping("/syncFlagByPhone")
    public Map<String,Object> syncFlagByPhone(@RequestBody SyncRequest syncRequest) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            Long[] productIds = syncRequest.getProductIds();
            if (syncRequest.getProductIds().length == 0) {
                productIds = new Long[]{0L};
            }
            // 更新同步的视频的同步状态为0
            deviceServiceImpl.updateSyncFlagToZero(syncRequest.getWe_openid());

            // 将产品ID数组的同步状态同步为1
            deviceServiceImpl.updateProductSyncStatus(productIds, syncRequest.getWe_openid());
            resultMap.put("code",200);
            resultMap.put("message","同步成功");
        }catch (Exception e){
            logger.error("小程序获取视频同步异常{}",e);
            resultMap.put("code",500);
            resultMap.put("message","服务器内部错误");
        }
        return resultMap;
    }

    /**
     * 设备登录接口
     *
     * @param loginRequest .user 账号为设备的唯一编码
     * @param loginRequest .pwd  密码为账号user的MD5的32加密
     * @return
     */
    @PostMapping("/appLogin")
    public String appLogin(@RequestBody AppLogin loginRequest) {
        String id = loginRequest.getId();
        String pwd = loginRequest.getPwd();
        Map<String, Object> resultMap = new HashMap<>();
        String uuid = "";
        String token = "";
        String code = "";
        String result = "";
        Gson gson = new Gson();
        try {
            int has = deviceServiceImpl.queryPwdByInOutStock(id, pwd);
            if (has == 1) {
                CaptchaResult captchaResult = captchaService.getCaptcha();
                if (captchaResult.isCaptchaEnabled()) {
                    code = captchaResult.getCodeStr();
                    uuid = captchaResult.getUuid();
                    // 这里的账号和密码是你指定的，不需要MD5加密
                    token = loginService.login("admin", "admin123", code, uuid);
                    resultMap.put("success", true);
                    resultMap.put("message", "访问成功");
                    Map<String, Object> dataMap = new HashMap<>();
                    dataMap.put("id", id);
                    dataMap.put("token", token);
                    resultMap.put("data", dataMap);
                    resultMap.put("code", 200);
                }

            } else {
                logger.error("设备登录异常{}","设备编号或者会员名称不存在");
                resultMap.put("success", false);
                resultMap.put("message", "设备编号或者会员名称不存在");
                resultMap.put("code", 505);
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("设备登录异常{}","服务器内部错误");
            resultMap.put("success", false);
            resultMap.put("message", "服务器内部错误");
            resultMap.put("code", 500);
        }
        result = gson.toJson(resultMap);
        System.out.println("我的Token--->" + token);
        System.out.println("我的Result--->" + result);
        return result;
    }

    /**
     * App心跳同步接口(视频)
     */
    @PostMapping("/syncHeartByHardware")
    public Map<String, Object> SyncHeartByHardware(@RequestBody Heart heart) {
        return deviceServiceImpl.syncHeartByHardware(heart);
    }

    /**
     * App心跳同步接口(直播)
     */
    @PostMapping("/syncLiveHeartByHardware")
    public Map<String, Object> SyncLiveHeartByHardware(@RequestBody LiveHeart heart) {
        return deviceServiceImpl.SyncLiveHeartByHardware(heart);
    }

    @PostMapping("/syncDeviceVideoId")
    public Map<String, Object> syncDeviceVideoId(@RequestBody VoiceVo voiceVo) {
        boolean isOk = deviceServiceImpl.syncDeviceVideoId(voiceVo);
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "同步完成");
        result.put("code", 200);
        return result;
    }

    @PostMapping("/syncDeviceAudioId")
    public Map<String, Object> syncDeviceAudioId(@RequestBody VoiceVo voiceVo) {
        boolean isOk = deviceServiceImpl.syncDeviceAudioId(voiceVo);
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "同步完成");
        result.put("code", 200);
        return result;
    }

    /**
     * 音频同步（般若之声）
     * @param heart
     * @return
     */
    @PostMapping("/syncVoiceByHardware")
    public Map<String, Object> syncVoiceByHardware(@RequestBody Heart heart) {
        return deviceServiceImpl.syncVoiceByHardware(heart);
    }

    /**
     * 单曲循环结束
     * @return
     */
    @PostMapping("/syncVoiceByOverTag")
    public Map<String, Object> syncVoiceByOverTag(@RequestBody VoiceTag voiceTag) {
        return deviceServiceImpl.syncVoiceByOverTag(voiceTag);
    }

    @PostMapping("/download/resource")
    public ResponseEntity<byte[]> resourceDownload(@RequestBody DownLoadResource downLoadResource, HttpServletResponse response) {
        String resource = downLoadResource.getResource();
        System.out.println("resource-------->"+resource);
        try {
            if (!checkAllowDownload(resource)) {
                logger.error("设备下载接口异常{}","资源文件({})非法，不允许下载。"+resource);
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。", resource));
            }

            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");

            System.out.println("下载路径 -----> " + downloadName);

            File file = new File(downloadPath);
            if (!file.exists() || downloadPath.equals("D:/Object/adv/files")) {
                System.out.println("----------视频下载失败----------");
                logger.error("设备下载接口异常{}","----------视频下载失败----------");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            } else {
                // 设置响应头
                response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadName + "\"");
                // 设置Content-Length响应头，告诉浏览器内容的大小
                response.setContentLength((int) file.length());

                // 使用InputStream读取文件
                try (InputStream inputStream = new FileInputStream(file);
                     OutputStream outputStream = response.getOutputStream()) {

                    // 创建一个缓冲区
                    byte[] buffer = new byte[102400];
                    int bytesRead;

                    // 读取文件并写入响应
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
//                        System.out.println("读取的大小: " + bytesRead);
                        outputStream.write(buffer, 0, bytesRead);
                    }

                    // 刷新并关闭流（实际上，由于使用了try-with-resources，流会自动关闭）
                    outputStream.flush();
                }

                // 返回空的ResponseEntity，因为数据已经写入响应
                return ResponseEntity.ok().build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("设备下载接口异常{}",e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    /**
     * 请求体类
     */
    public static class SyncRequest {
        private Long[] productIds;
        private String we_openid;

        public Long[] getProductIds() {
            return productIds;
        }

        public void setProductIds(Long[] productIds) {
            this.productIds = productIds;
        }

        public String getWe_openid() {
            return we_openid;
        }

        public void setWe_openid(String we_openid) {
            this.we_openid = we_openid;
        }
    }

}
